let BaseController = require('./BaseController')
let fs = require('fs')
let path = require('path')
/**
 * 获取每天数据，按日期命名
 */
class 每日龙虎榜Controller extends BaseController {
    constructor() {
        super();
        this.baseSrc = `d:/数据指标分类/${new Date().format('yyyyMMdd')}/待入库/06日龙虎榜/每日龙虎榜/`
        this.encode = 'GBK'
        this.data = [];
    }
    /**
     * 获取url
     */
    getUrl(date) {
        return `http://data.eastmoney.com/DataCenter_V3/stock2016/TradeDetail/pagesize=50,page=1,sortRule=-1,sortType=,startDate=${date},endDate=${date},gpfw=0,js=var%20data_tab_2.html`
    }

    /**
     * 获取历史数据
     */
    async getHistory() {
        console.log('1每日龙虎榜Controller')
        try {
            this.startDate = new Date(this.startDate).format('yyyy-MM-dd')
            if (new Date() >= new Date(this.startDate)) {
                console.log(this.startDate)
                let data = await this.getData(this.startDate, this.isCache)
                data = this.axiosDataFormat(data.toString());
                this.writeCsv(data);
                this.startDate = this.addDate(this.startDate, 1)
                await this.getHistory();
            }
        } catch (err) {
            console.log(err)
            await this.getHistory();
        }

    }

    outputDataFormat(arr) {
        let temp = {}
        for (let i = 0; i < arr.length; i++) {
            if (i == 0) {
                arr[i].index = 0
                temp.code = arr[i].SCode;
                temp.index = 0;
            } else {
                if (arr[i].SCode === temp.code) {
                    temp.index++;
                    arr[i].index = temp.index
                } else {
                    arr[i].index = 0
                    temp.code = arr[i].SCode;
                    temp.index = 0;
                }
            }

        }
        return arr;
    }
    /**
     * 数据格式化
     */
    axiosDataFormat(data) {
        return JSON.parse(data.replace('var data_tab_2=', '')).data
    }
    /**
     * 写csv
     */
    writeCsv(arr) {
        if (!fs.existsSync(this.baseSrc)) {
            this.mkdirs(this.baseSrc)
        }
        this.file = `每日龙虎榜_${new Date(this.startDate).format('yyyyMMdd')}.csv`
        fs.writeFileSync(path.join(this.baseSrc, this.file), this.convertToCSV(arr, 'title'), 'UTF-8')
    }

    async main(startDate = '2015-01-01', isCache = true) {
        this.startDate = startDate;
        this.isCache = isCache;
        console.log('--->执行1每日龙虎榜Controller')
        await this.getHistory()
    }
}

let controller = new 每日龙虎榜Controller()
// controller.main(controller.addDate(new Date(), -2))
module.exports = controller